`
https://leetcode.cn/problems/complete-binary-tree-inserter/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 */
var CBTInserter = function (root) {
  // 这个队列只记录完全二叉树底部可以进行插入的节点
  this.q = [];
  this.root = root;

  // 进行普通的 BFS，目的是找到底部可插入的节点
  let temp = [root];
  while (temp.length > 0) {
    let cur = temp.shift();
    if (cur.left !== null) {
      temp.push(cur.left);
    }
    if (cur.right !== null) {
      temp.push(cur.right);
    }
    if (cur.right === null || cur.left === null) {
      // 找到完全二叉树底部可以进行插入的节点
      this.q.push(cur);
    }
  }
};

/** 
* @param {number} val
* @return {number}
*/
CBTInserter.prototype.insert = function (val) {
  let node = new TreeNode(val);
  let cur = this.q[0];
  // 进行插入
  if (cur.left === null) {
    cur.left = node;
  } else if (cur.right === null) {
    cur.right = node;
    this.q.shift();
  }
  // 新节点的左右节点也是可以插入的
  this.q.push(node);
  return cur.val;
};

/**
* @return {TreeNode}
*/
CBTInserter.prototype.get_root = function () {
  return this.root
};

/** 
* Your CBTInserter object will be instantiated and called as such:
* var obj = new CBTInserter(root)
* var param_1 = obj.insert(val)
* var param_2 = obj.get_root()
*/